package com.evan.idempotent.storage.idempotentstorageimpl;

import com.evan.idempotent.enums.IdempotentStorageTypeEnum;
import com.evan.idempotent.storage.IdempotentStorage;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

import static com.evan.idempotent.constants.IdempotentConstants.IDEMPOTENT_DEFAULT_VALUE;

/**
 * @Description: redis存储
 * @Author liudeguang
 */
@Slf4j
public class IdempotentStorageRedis implements IdempotentStorage {


    @Autowired
    private RedissonClient redissonClient;


    @Override
    public IdempotentStorageTypeEnum type() {
        return IdempotentStorageTypeEnum.REDIS;
    }

    @Override
    public void setValue(String key, String value, long expireTime, TimeUnit timeUnit) {
        log.info("IdempotentStorageRedis-setValue Redis Set key:{}, Value:{}, expireTime:{}, timeUnit:{}", key, value, expireTime, timeUnit);
        RBucket<String> bucket = redissonClient.getBucket(key);
        if (bucket != null) {
            bucket.set(value, expireTime, timeUnit);
        }
    }

    @Override
    public String getValue(String key) {
        RBucket<String> bucket = redissonClient.getBucket(key);
        String value = bucket.get();
        log.info("IdempotentStorageRedis-getValue Redis Get key:{}, Value:{}", key, value);
        return value;
    }

    @Override
    public Boolean verify(String key, long expireTime, TimeUnit timeUnit) {
        return (redissonClient).getBucket(key).trySet(IDEMPOTENT_DEFAULT_VALUE, expireTime, timeUnit);
    }
}
